///@Description(描述)     测试BasePage的页面
///@author(作者)          zhangyinhong
///@create(时间)          2025-01-20 10:30

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:app_core/app_core.dart';
import 'app_base_page.dart';
import 'base_test_logic.dart';
import '../router/app_routers.dart';
import '../widgets/empty_state_widget.dart';

class BaseTestPage extends AppBasePage<BaseTestLogic> {
  BaseTestPage({super.key});

  // @override
  final logic = Get.put(BaseTestLogic());

  @override
  String? get title => 'Base测试页面';

  @override
  Widget? get rightWidget => IconButton(icon: const Icon(Icons.refresh), onPressed: () => logic.onRefresh(), tooltip: '刷新数据');

  @override
  Widget buildContent(BuildContext context) {
    return wrapWithRefresh(
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildUserInfoSection(),
            const SizedBox(height: 24),
            _buildCounterSection(),
            const SizedBox(height: 24),
            _buildTodoSection(),
            const SizedBox(height: 24),
            _buildActionButtons(),
          ],
        ),
      ),
      onRefresh: logic.onRefresh,
    );
  }

  /// 用户信息区域
  Widget _buildUserInfoSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('用户信息', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 12),
            Obx(() {
              final userInfo = logic.userInfo.value;
              if (userInfo == null) {
                return const Text('用户信息加载中...', style: TextStyle(color: Colors.grey));
              }
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      CircleAvatar(
                        radius: 25,
                        backgroundColor: Colors.blue,
                        child: Text(userInfo.name.isNotEmpty ? userInfo.name[0] : 'U', style: const TextStyle(color: Colors.white, fontSize: 20)),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(userInfo.name, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
                            Text(userInfo.email, style: const TextStyle(color: Colors.grey)),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  ElevatedButton(onPressed: () => _showUpdateNameDialog(), child: const Text('修改用户名')),
                ],
              );
            }),
          ],
        ),
      ),
    );
  }

  /// 计数器区域
  Widget _buildCounterSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('计数器测试', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 12),
            Obx(() {
              return Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('当前计数: ${logic.counter.value}', style: const TextStyle(fontSize: 16)),
                  Row(
                    children: [
                      ElevatedButton(onPressed: logic.decrementCounter, child: const Text('-')),
                      const SizedBox(width: 8),
                      ElevatedButton(onPressed: logic.incrementCounter, child: const Text('+')),
                    ],
                  ),
                ],
              );
            }),
          ],
        ),
      ),
    );
  }

  /// 待办事项区域
  Widget _buildTodoSection() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('待办事项', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                ElevatedButton.icon(onPressed: () => _showAddTodoDialog(), icon: const Icon(Icons.add), label: const Text('添加')),
              ],
            ),
            const SizedBox(height: 12),
            Obx(() {
              final todoList = logic.todoList;

              if (todoList.isEmpty) {
                return EmptyStateWidget.listEmpty(actionText: '添加待办事项', onAction: _addTodoItem);
              }

              return Column(children: todoList.map((item) => _buildTodoItem(item)).toList());
            }),
          ],
        ),
      ),
    );
  }

  /// 单个待办事项
  Widget _buildTodoItem(TodoItem item) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(border: Border.all(color: Colors.grey.shade300), borderRadius: BorderRadius.circular(8)),
      child: ListTile(
        leading: Checkbox(value: item.isCompleted, onChanged: (value) => logic.toggleTodoItem(item.id)),
        title: Text(
          item.title,
          style: TextStyle(decoration: item.isCompleted ? TextDecoration.lineThrough : null, color: item.isCompleted ? Colors.grey : null),
        ),
        trailing: IconButton(icon: const Icon(Icons.delete, color: Colors.red), onPressed: () => _showDeleteConfirmDialog(item)),
      ),
    );
  }

  /// 操作按钮区域
  Widget _buildActionButtons() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('测试操作', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 12),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton(
                  onPressed: () {
                    YHSmartDialog.showLoading(message: '测试加载中...');
                    Future.delayed(const Duration(seconds: 2), () {
                      YHSmartDialog.dismiss();
                      YHSmartDialog.showSuccessMsg('加载完成！');
                    });
                  },
                  child: const Text('测试Loading'),
                ),
                ElevatedButton(
                  onPressed: () => YHSmartDialog.showErrorMsg('这是一个测试错误信息'),
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                  child: const Text('测试Error'),
                ),
                ElevatedButton(
                  onPressed: () => YHSmartDialog.showMsg('暂无数据'),
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.orange),
                  child: const Text('测试Empty'),
                ),
                ElevatedButton(onPressed: () => logic.onRefresh(), style: ElevatedButton.styleFrom(backgroundColor: Colors.green), child: const Text('重新加载')),
                ElevatedButton(
                  onPressed: () => Get.toNamed(AppRouters.emptyExample.r),
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.purple),
                  child: const Text('测试空页面'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 显示修改用户名对话框
  void _showUpdateNameDialog() {
    final controller = TextEditingController(text: logic.userInfo.value?.name ?? '');

    Get.dialog(
      AlertDialog(
        title: const Text('修改用户名'),
        content: TextField(controller: controller, decoration: const InputDecoration(labelText: '新用户名', border: OutlineInputBorder())),
        actions: [
          TextButton(onPressed: () => Get.back(), child: const Text('取消')),
          ElevatedButton(
            onPressed: () {
              logic.updateUserName(controller.text);
              Get.back();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示添加待办事项对话框
  void _showAddTodoDialog() {
    final controller = TextEditingController();

    Get.dialog(
      AlertDialog(
        title: const Text('添加待办事项'),
        content: TextField(controller: controller, decoration: const InputDecoration(labelText: '待办事项内容', border: OutlineInputBorder()), autofocus: true),
        actions: [
          TextButton(onPressed: () => Get.back(), child: const Text('取消')),
          ElevatedButton(
            onPressed: () {
              logic.addTodoItem(controller.text);
              Get.back();
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }

  /// 显示删除确认对话框
  void _showDeleteConfirmDialog(TodoItem item) {
    Get.dialog(
      AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除「${item.title}」吗？'),
        actions: [
          TextButton(onPressed: () => Get.back(), child: const Text('取消')),
          ElevatedButton(
            onPressed: () {
              logic.deleteTodoItem(item.id);
              Get.back();
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 添加待办事项
  static void _addTodoItem() {
    final controller = TextEditingController();

    Get.dialog(
      AlertDialog(
        title: const Text('添加待办事项'),
        content: TextField(controller: controller, decoration: const InputDecoration(labelText: '待办事项内容', border: OutlineInputBorder()), autofocus: true),
        actions: [
          TextButton(onPressed: () => Get.back(), child: const Text('取消')),
          ElevatedButton(
            onPressed: () {
              Get.find<BaseTestLogic>().addTodoItem(controller.text);
              Get.back();
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }
}
